<template>
	<el-card>
		<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList()">
			<el-form-item>
				<el-input v-model="state.queryForm.username" style="width: 120px" placeholder="用户名" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<el-input v-model="state.queryForm.mobile" placeholder="手机号" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<fast-select v-model="state.queryForm.userType" dict-type="user_type" clearable placeholder="用户类型"></fast-select>
			</el-form-item>
      <el-form-item >
        <el-tree-select
            v-model="state.queryForm.orgId"
            :data="orgList"
            value-key="id"
            placeholder="所属机构"
            check-strictly
            @change="orgHandle($event)"
            :render-after-expand="false"
            :props="{ label: 'name', children: 'children' }"
            style="width: 150px"
        />
      </el-form-item>
			<el-form-item>
				<el-button @click="getDataList()">查询</el-button>
			</el-form-item>
      <el-form-item>
        <el-button @click="resetDataList()">重置</el-button>
      </el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:user:save'" type="primary" @click="addOrUpdateHandle()">新增</el-button>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:user:delete'" type="danger" @click="deleteBatchHandle()">删除</el-button>
			</el-form-item>
<!--			<el-form-item v-auth="'sys:user:import'">
				<el-upload :action="uploadUserExcelUrl" :before-upload="beforeUpload" :on-success="handleSuccess" :show-file-list="false">
					<el-button type="info">导入</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item>
				<el-button v-auth="'sys:user:export'" type="success" @click="downloadExcel()">导出</el-button>
			</el-form-item>-->
		</el-form>
		<el-table
			v-loading="state.dataListLoading"
			show-overflow-tooltip
			:data="state.dataList"
			border
			style="width: 100%"
			@selection-change="selectionChangeHandle"
		>
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column prop="username" label="用户名" header-align="center" align="center"></el-table-column>
			<el-table-column prop="realName" label="姓名" header-align="center" align="center"></el-table-column>
			<fast-table-column prop="gender" label="性别" dict-type="user_gender"></fast-table-column>
			<el-table-column prop="mobile" label="手机号" header-align="center" align="center"></el-table-column>
			<el-table-column prop="email" label="邮箱" header-align="center" align="center"></el-table-column>
      <fast-table-column prop="userType" label="用户类型"  dict-type="user_type" ></fast-table-column>
			<el-table-column prop="orgName" label="所属机构" header-align="center" align="center"></el-table-column>
      <el-table-column prop="communityName" label="所属社区" header-align="center" align="center"></el-table-column>
<!--      <fast-table-column prop="superAdmin" label="管理员" dict-type="user_super_admin"></fast-table-column>-->
<!--			<fast-table-column prop="status" label="状态" dict-type="user_status"></fast-table-column>-->
      <el-table-column
          label="状态"
          header-align="center" align="center"
      >
        <template #default="scope">
          <span v-html="getDictLabelList('user_status', scope.row.status)" @click="updateStatus(scope.row)"></span>
        </template>
      </el-table-column>

			<el-table-column prop="createTime" label="创建时间" header-align="center" align="center" width="170"></el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="center" width="150">
				<template #default="scope">
					<el-button v-auth="'sys:user:update'" type="primary" link @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
					<el-button v-auth="'sys:user:delete'" type="primary" link @click="deleteBatchHandle(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.limit"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>

		<!-- 弹窗, 新增 / 修改 -->
		<add-or-update ref="addOrUpdateRef" @refresh-data-list="getDataList"></add-or-update>
	</el-card>
</template>

<script setup lang="ts" name="SysUserIndex">
import { useCrud } from '@/hooks'
import {onMounted, reactive, ref} from 'vue'
import AddOrUpdate from './add-or-update.vue'
import { IHooksOptions } from '@/hooks/interface'
import { ElMessage, UploadProps } from 'element-plus'
import cache from '@/utils/cache'
import constant from '@/utils/constant'
import {useUserStore} from "@/store/modules/user";
import {merchantListApi} from "@/api/sys/merchant";
import {useOrgListApi, useOrgMerchantApi} from "@/api/sys/orgs";
import { getDictLabelList } from '@/utils/tool'
import {useUserApi, useUserSubmitApi} from "@/api/sys/user";

const state: IHooksOptions = reactive({
	dataListUrl: '/sys/user/page',
	deleteUrl: '/sys/user',
	queryForm: {
		username: '',
		mobile: '',
		gender: '',
    orgId: '',
    userType: '',
    merchantId: ''
	}
})
const dataForm = reactive({
  status: 1
})

const userStore = useUserStore()
const merchantList = ref([])
const orgList = ref([])

const init = async () => {
  getOrgList()
}

onMounted( () =>{
  init()
})

const addOrUpdateRef = ref()

const addOrUpdateHandle = (id?: number) => {
	addOrUpdateRef.value.init(id)
}

// 获取机构列表
const getOrgList = () => {
  return useOrgListApi().then(res => {
    orgList.value = res.data
  })
}

const orgHandle = (val: any) => {

}

const updateStatus = (row: any) => {
  console.log(11111)
  useUserApi(row.id).then(res => {
    Object.assign(dataForm, res.data)
    if(row.status==0){
      dataForm.status=1
    }else if(row.status==1){
      dataForm.status=0
    }
    useUserSubmitApi(dataForm).then(() => {
      ElMessage.success({
        message: '操作成功',
        duration: 500,
        onClose: () => {
          getDataList()
        }
      })
    })
  })


}

const merchantHandle = (val: any) => {
  getOrgMerchantList(val)
}

// 获取商户列表
const getMerchantList = async () => {
  const res = await merchantListApi()
  merchantList.value = res.data
}


// 获取商户下机构列表
const getOrgMerchantList = (merchantId: number) => {
  useOrgMerchantApi(merchantId).then(res => {
    orgList.value = res.data
    console.log(orgList.value)
  })
}

// 导入用户excel文件
const uploadUserExcelUrl = constant.apiUrl + '/sys/user/import?access_token=' + cache.getToken()

const downloadExcel = () => {
	downloadHandle('/sys/user/export')
}

const handleSuccess: UploadProps['onSuccess'] = (res, file) => {
	if (res.code !== 0) {
		ElMessage.error('上传失败：' + res.msg)
		return false
	}

	ElMessage.success({
		message: '上传成功',
		duration: 500,
		onClose: () => {
			getDataList()
		}
	})
}

const resetDataList = () =>{
  state.queryForm = {}
  state.queryForm.userType = ''
  state.queryForm.gender = ''
  getDataList()
}

const beforeUpload: UploadProps['beforeUpload'] = file => {
	if (file.size / 1024 / 1024 / 1024 / 1024 > 1) {
		ElMessage.error('文件大小不能超过100M')
		return false
	}
	return true
}

defineExpose({
  init
})

const { getDataList, selectionChangeHandle, sizeChangeHandle, currentChangeHandle, deleteBatchHandle, downloadHandle } = useCrud(state)
</script>
